<?php
/**
 * API数字签名
 */
namespace DigitalSignature;

class DigitalSignature
{
    #待签名数组
    private $data;
    #前端传递过来的sign
    protected $html_sign;
    /**
     * @$data array 待签名的数组
     */
    public function __construct($data,$html_sign)
    {
        $this->data=$data;
        $this->html_sign = $html_sign;
    }
    #数字签名验证
    public function checkSign()
    {
        $data = $this->data;
        if($this->html_sign == FALSE)
        {
            returnJson(-1101,"sign不能为空");
        }
        if(empty($data['timestamp']))
        {
            returnJson(-1102,"timestamp不能为空");
        }
        //请求仅在30s有效
        if( abs($data['timestamp'] - time()) >=30 )
        {
//            returnJson(-1103,  "当前url请求超时");
        }
        #服务端生成签名
        $php_sign = self::getSign();
        #校验签名
        if( $php_sign !== $this->html_sign)
        {
            returnJson(-1104,"数字签名校验失败");
        }

    }
    #服务端生成签名
    private function getSign()
    {
        $str = self::toBeSignedStr($this->data);
        #利用待签名字符串生成签名
        return strtoupper(MD5($str));
    }
    /*
     *生成待签名字符串
     */
    private function toBeSignedStr( $data )
    {
        $str = self::formatBizQueryParaMap($data, true);
        #得到待签名字符串
        $str = $str."&key=nice123456@@";
        return $str;
    }
    /**
     * 排序数组和对参数名及参数值进行URL编码
     */
    private function formatBizQueryParaMap($param, $bool)
    {
        $buff = "";
        ksort($param);
        foreach ($param as $k => $v)
        {
            if($bool)
            {
                $v = urlencode($v);
                $k = urlencode($k);
            }
            $buff .= $k . "=" . $v . "&";
        }
        $reqPar = "";
        if (strlen($buff) > 0)
        {
            $reqPar = substr($buff, 0, strlen($buff)-1);
        }
        return $reqPar;
    }

}